import { ref, onMounted, readonly } from 'vue';
import { useToast } from "vue-toastification";
// import { useI18n } from 'vue-i18n'; // Disable i18n
import { defineComponent } from 'vue'; // Needed for toast component API if we bring it back

interface BrowserInfo {
    name: string;
    version: number | null;
    icon: string; // Now represents the icon filename base (lowercase)
}

interface Requirements {
    chrome: number;
    edge: number;
    firefox: number;
    safari: number | string;
}

// Element Plus 2.5.0+ requirements
const elementPlusMinVersions: Requirements = {
    chrome: 85,
    edge: 85,
    firefox: 79,
    safari: 14.1,
};

// :has() pseudo-class requirements (approximate based on MDN/CanIUse)
const hasPseudoClassMinVersions: Requirements = {
    chrome: 105,
    edge: 105,
    firefox: 121,
    safari: 15.4,
};

const parseUserAgent = (ua: string): BrowserInfo => {
    let name = 'Unknown';
    let version: number | null = null;
    let icon = 'severityknown'; // Use the actual filename for the default icon
    let match: RegExpMatchArray | null;

    // Check for Opera (OPR) BEFORE Chrome, as UA may contain both
    if ((match = ua.match(/(?:OPR|Opera)\/(\d+)/))) { 
        name = 'Opera';
        version = parseInt(match[1], 10);
        icon = 'opera';
    } else if ((match = ua.match(/Edg\/(\d+)/))) {
        name = 'Edge';
        version = parseInt(match[1], 10);
        icon = 'edge';
    } else if ((match = ua.match(/(?:Chrome|CriOS)\/(\d+)/))) {
        // Exclude Edge and Opera if already matched
        if (!ua.includes("Edg/") && !ua.includes("OPR/") && !ua.includes("Opera/")) {
            name = 'Chrome';
            version = parseInt(match[1], 10);
            icon = 'chrome';
        }
    } else if ((match = ua.match(/Firefox\/(\d+)/))) {
        name = 'Firefox';
        version = parseInt(match[1], 10);
        icon = 'firefox';
    } else if ((match = ua.match(/Version\/(\d+(\.\d+)?).*Safari/))) {
        // Exclude Chrome/Edge which also contain Safari string
        if (!ua.includes("Chrome") && !ua.includes("CriOS") && !ua.includes("Edg/")) {
            name = 'Safari';
            version = parseFloat(match[1]);
            icon = 'safari';
        }
    } else if ((match = ua.match(/MSIE (\d+)/)) || (match = ua.match(/Trident.*rv:(\d+)/))) {
        name = 'IE';
        version = parseInt(match[1], 10);
        // Assuming filename is ie.svg
        icon = 'ie'; // Use 'ie' as identifier
    }

    return { name, version, icon };
};

export function useBrowserCompatibility() {
    const browserInfo = ref<BrowserInfo>({ name: 'Unknown', version: null, icon: 'severityknown' });
    const isSupported = ref<boolean | null>(null); // For overall app support
    const requiresTransitionWarning = ref<boolean>(false);
    const requiresHasPseudoClassWarning = ref<boolean>(false); // New state for :has() warning
    // const { t } = useI18n(); // Disable i18n
    const toast = useToast();

    const checkCompatibility = () => {
        browserInfo.value = parseUserAgent(navigator.userAgent);
        const { name, version } = browserInfo.value;

        let meetsMinRequirements = false;
        let meetsHasPseudoClassRequirements = false; // Check for :has() support

        if (version !== null) {
            const reqSafariVersion = typeof elementPlusMinVersions.safari === 'string'
                ? parseFloat(elementPlusMinVersions.safari)
                : elementPlusMinVersions.safari;
            const reqHasSafariVersion = typeof hasPseudoClassMinVersions.safari === 'string'
                ? parseFloat(hasPseudoClassMinVersions.safari)
                : hasPseudoClassMinVersions.safari;

            switch (name) {
                case 'Chrome': 
                    meetsMinRequirements = version >= elementPlusMinVersions.chrome; 
                    meetsHasPseudoClassRequirements = version >= hasPseudoClassMinVersions.chrome;
                    break;
                case 'Edge': 
                    meetsMinRequirements = version >= elementPlusMinVersions.edge; 
                    meetsHasPseudoClassRequirements = version >= hasPseudoClassMinVersions.edge;
                    break;
                case 'Firefox': 
                    meetsMinRequirements = version >= elementPlusMinVersions.firefox; 
                    meetsHasPseudoClassRequirements = version >= hasPseudoClassMinVersions.firefox;
                    break;
                case 'Safari': 
                    meetsMinRequirements = version >= reqSafariVersion; 
                    meetsHasPseudoClassRequirements = version >= reqHasSafariVersion;
                    break;
                case 'IE': 
                    meetsMinRequirements = false; 
                    meetsHasPseudoClassRequirements = false;
                    break;
                // Consider Opera based on Chrome version? Needs confirmation
                case 'Opera': // Assuming Opera follows Chrome's :has() support timeline based on Chromium engine
                     meetsMinRequirements = version >= elementPlusMinVersions.chrome; // Check against Chrome req for base features
                     meetsHasPseudoClassRequirements = version >= hasPseudoClassMinVersions.chrome; // Check against Chrome req for :has()
                     break;
                default: 
                    meetsMinRequirements = false; 
                    meetsHasPseudoClassRequirements = false;
                    break;
            }
        } else {
            meetsMinRequirements = false;
            meetsHasPseudoClassRequirements = false;
        }

        isSupported.value = meetsMinRequirements;

        // Check for transition warning ONLY if minimum requirements are met
        if (meetsMinRequirements) {
            const isTransitionAPISupported = typeof (document as any).startViewTransition === 'function';
            const dismissedTransitionKey = 'dismissedTransitionWarning';
            const dismissedTransitionValue = localStorage.getItem(dismissedTransitionKey);
            if (!isTransitionAPISupported && dismissedTransitionValue !== 'true') {
                requiresTransitionWarning.value = true;
            }
        }

        // Check for :has() warning (can happen even if min requirements are met)
        if (!meetsHasPseudoClassRequirements) {
             const dismissedHasKey = 'dismissedHasPseudoClassWarning';
             const dismissedHasValue = localStorage.getItem(dismissedHasKey);
             if (dismissedHasValue !== 'true') {
                 requiresHasPseudoClassWarning.value = true;
             }
        }
    };

    const showTransitionWarningToast = () => {
        if (!requiresTransitionWarning.value) return;

        // Use setTimeout to ensure toast system is ready
        setTimeout(() => {
            // const warningTitle = t('compatibility.transitionWarningTitle') // Disable i18n
            // const warningDescription = t('compatibility.transitionWarningDescription') // Disable i18n
            const warningTitle = '视觉效果可能受限' // Hardcoded string
            const warningDescription = '您当前的浏览器不支持 View Transition API，部分界面（如主题切换）可能缺少平滑的过渡动画，但这不影响核心功能。' // Hardcoded string
            toast.warning(
                // Keep plain string for simplicity for now
                `${warningTitle}: ${warningDescription}`,
                {
                    timeout: 10000,
                    closeOnClick: false,
                    onClose: () => {
                        try {
                            localStorage.setItem('dismissedTransitionWarning', 'true')
                        } catch (e) {
                            console.warn('Failed to save transition warning dismissal state:', e)
                        }
                        requiresTransitionWarning.value = false; // Update state if closed
                    }
                }
            );
        }, 100); // Shorter delay might be sufficient now
    };

    // New function for :has() warning toast
    const showHasPseudoClassWarningToast = () => {
        if (!requiresHasPseudoClassWarning.value) return;

        setTimeout(() => {
            const warningTitle = ':has() 选择器支持受限' // Hardcoded string
            const warningDescription = '您当前的浏览器可能不支持 :has() CSS 选择器，文件管理器等界面的部分样式可能显示不正确，但这不影响核心功能。' // Hardcoded string
            const dismissedKey = 'dismissedHasPseudoClassWarning';
            
            toast.warning(
                `${warningTitle}: ${warningDescription}`,
                {
                    timeout: 10000, // Longer timeout for this warning
                    closeOnClick: false,
                    onClose: () => {
                        try {
                            localStorage.setItem(dismissedKey, 'true')
                        } catch (e) {
                            console.warn('Failed to save :has() warning dismissal state:', e)
                        }
                        requiresHasPseudoClassWarning.value = false; // Update state
                    }
                }
            );
        }, 150); // Slightly longer delay than the transition warning
    };
    
    // Run check on composable initialization
    checkCompatibility();

    // Expose required data and functions
    return {
        isSupported: readonly(isSupported),
        browserInfo: readonly(browserInfo),
        requiresTransitionWarning: readonly(requiresTransitionWarning),
        requiresHasPseudoClassWarning: readonly(requiresHasPseudoClassWarning), // Expose new state
        showTransitionWarningToast,
        showHasPseudoClassWarningToast // Expose new function
    };
}

export const getRequiredVersionsString = (): string => {
    return `Chrome ${elementPlusMinVersions.chrome}+, Edge ${elementPlusMinVersions.edge}+, Firefox ${elementPlusMinVersions.firefox}+, Safari ${elementPlusMinVersions.safari}+`;
}; 